<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户注册 - 工单管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #007bff;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
            --gradient-bg: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        body {
            background: var(--gradient-bg);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .register-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .register-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            overflow: hidden;
            max-width: 500px;
            width: 100%;
        }

        .register-header {
            background: var(--primary-color);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
        }

        .register-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, rgba(255,255,255,0.1) 0%, transparent 100%);
        }

        .register-header h2 {
            margin: 0;
            font-weight: 600;
            position: relative;
            z-index: 1;
        }

        .register-header p {
            margin: 10px 0 0 0;
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }

        .register-form {
            padding: 30px;
        }

        .form-floating {
            margin-bottom: 20px;
        }

        .form-floating input, .form-floating select {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
        }

        .form-floating input:focus, .form-floating select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }

        .form-floating input.is-invalid {
            border-color: var(--danger-color);
        }

        .form-floating input.is-valid {
            border-color: var(--success-color);
        }

        .invalid-feedback {
            display: block;
            font-size: 0.875em;
            color: var(--danger-color);
            margin-top: 5px;
        }

        .valid-feedback {
            display: block;
            font-size: 0.875em;
            color: var(--success-color);
            margin-top: 5px;
        }

        .btn-register {
            width: 100%;
            padding: 12px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 16px;
            transition: all 0.3s ease;
            border: none;
            position: relative;
            overflow: hidden;
        }

        .btn-register::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        .btn-register:hover::before {
            left: 100%;
        }

        .btn-register:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .loading-spinner {
            display: none;
            width: 20px;
            height: 20px;
            border: 2px solid #ffffff;
            border-top: 2px solid transparent;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .alert {
            border-radius: 10px;
            border: none;
            margin-bottom: 20px;
        }

        .password-strength {
            margin-top: 5px;
            font-size: 0.875em;
        }

        .strength-weak { color: var(--danger-color); }
        .strength-medium { color: var(--warning-color); }
        .strength-strong { color: var(--success-color); }

        .login-link {
            text-align: center;
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .login-link a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 600;
        }

        .login-link a:hover {
            text-decoration: underline;
        }

        .role-info {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            font-size: 0.9em;
            color: #6c757d;
        }

        @media (max-width: 480px) {
            .register-container {
                padding: 10px;
            }
            
            .register-card {
                border-radius: 15px;
            }
            
            .register-header {
                padding: 20px;
            }
            
            .register-form {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="register-card">
            <!-- 注册头部 -->
            <div class="register-header">
                <h2><i class="fas fa-user-plus me-2"></i>用户注册</h2>
                <p>创建您的工单管理系统账号</p>
            </div>

            <!-- 注册表单 -->
            <div class="register-form">
                <form id="registerForm">
                    <div class="alert alert-danger" id="errorAlert" style="display: none;">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <span id="errorMessage"></span>
                    </div>

                    <div class="alert alert-success" id="successAlert" style="display: none;">
                        <i class="fas fa-check-circle me-2"></i>
                        <span id="successMessage"></span>
                    </div>

                    <!-- 用户名 -->
                    <div class="form-floating">
                        <input type="text" class="form-control" id="username" name="username" placeholder="用户名" required>
                        <label for="username"><i class="fas fa-user me-2"></i>用户名</label>
                        <div class="invalid-feedback" id="usernameError"></div>
                    </div>

                    <!-- 密码 -->
                    <div class="form-floating">
                        <input type="password" class="form-control" id="password" name="password" placeholder="密码" required>
                        <label for="password"><i class="fas fa-lock me-2"></i>密码</label>
                        <div class="password-strength" id="passwordStrength"></div>
                        <div class="invalid-feedback" id="passwordError"></div>
                    </div>

                    <!-- 确认密码 -->
                    <div class="form-floating">
                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" placeholder="确认密码" required>
                        <label for="confirmPassword"><i class="fas fa-lock me-2"></i>确认密码</label>
                        <div class="invalid-feedback" id="confirmPasswordError"></div>
                    </div>

                    <!-- 真实姓名 -->
                    <div class="form-floating">
                        <input type="text" class="form-control" id="fullName" name="fullName" placeholder="真实姓名" required>
                        <label for="fullName"><i class="fas fa-id-card me-2"></i>真实姓名</label>
                        <div class="invalid-feedback" id="fullNameError"></div>
                    </div>

                    <!-- 邮箱 -->
                    <div class="form-floating">
                        <input type="email" class="form-control" id="email" name="email" placeholder="邮箱地址" required>
                        <label for="email"><i class="fas fa-envelope me-2"></i>邮箱地址</label>
                        <div class="invalid-feedback" id="emailError"></div>
                    </div>

                    <!-- 手机号 -->
                    <div class="form-floating">
                        <input type="tel" class="form-control" id="phone" name="phone" placeholder="手机号（可选）">
                        <label for="phone"><i class="fas fa-phone me-2"></i>手机号（可选）</label>
                        <div class="invalid-feedback" id="phoneError"></div>
                    </div>

                    <!-- 角色选择 -->
                    <div class="form-floating">
                        <select class="form-control" id="role" name="role" required>
                            <option value="">请选择角色</option>
                            <option value="CUSTOMER">客户</option>
                            <option value="AGENT">客服人员</option>
                        </select>
                        <label for="role"><i class="fas fa-user-tag me-2"></i>用户角色</label>
                        <div class="invalid-feedback" id="roleError"></div>
                    </div>

                    <!-- 角色说明 -->
                    <div class="role-info">
                        <strong>角色说明：</strong><br>
                        • <strong>客户</strong>：可以提交工单、查看反馈、发表评论<br>
                        • <strong>客服人员</strong>：可以处理工单、回复客户、管理反馈<br>
                        • <strong>管理员</strong>：需要联系系统管理员开通
                    </div>

                    <!-- 部门（可选） -->
                    <div class="form-floating">
                        <input type="text" class="form-control" id="department" name="department" placeholder="部门（可选）">
                        <label for="department"><i class="fas fa-building me-2"></i>部门（可选）</label>
                    </div>

                    <!-- 职位（可选） -->
                    <div class="form-floating">
                        <input type="text" class="form-control" id="position" name="position" placeholder="职位（可选）">
                        <label for="position"><i class="fas fa-briefcase me-2"></i>职位（可选）</label>
                    </div>

                    <!-- 工号（可选） -->
                    <div class="form-floating">
                        <input type="text" class="form-control" id="employeeId" name="employeeId" placeholder="工号（可选）">
                        <label for="employeeId"><i class="fas fa-id-badge me-2"></i>工号（可选）</label>
                    </div>

                    <button type="submit" class="btn btn-primary btn-register" id="registerBtn">
                        <div class="loading-spinner" id="loadingSpinner"></div>
                        <span id="registerText">注册账号</span>
                    </button>
                </form>

                <!-- 登录链接 -->
                <div class="login-link">
                    <p>已有账号？<a href="login.html">立即登录</a></p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        const API_BASE_URL = 'http://localhost:9090/api';

        // DOM 元素
        const registerForm = document.getElementById('registerForm');
        const registerBtn = document.getElementById('registerBtn');
        const loadingSpinner = document.getElementById('loadingSpinner');
        const registerText = document.getElementById('registerText');
        const errorAlert = document.getElementById('errorAlert');
        const errorMessage = document.getElementById('errorMessage');
        const successAlert = document.getElementById('successAlert');
        const successMessage = document.getElementById('successMessage');

        // 表单字段
        const usernameInput = document.getElementById('username');
        const passwordInput = document.getElementById('password');
        const confirmPasswordInput = document.getElementById('confirmPassword');
        const fullNameInput = document.getElementById('fullName');
        const emailInput = document.getElementById('email');
        const phoneInput = document.getElementById('phone');
        const roleSelect = document.getElementById('role');

        // 密码强度检查
        function checkPasswordStrength(password) {
            const strengthDiv = document.getElementById('passwordStrength');
            if (!password) {
                strengthDiv.textContent = '';
                return;
            }

            let score = 0;
            let feedback = [];

            if (password.length >= 6) score++;
            else feedback.push('至少6个字符');

            if (/[a-z]/.test(password)) score++;
            else feedback.push('包含小写字母');

            if (/[A-Z]/.test(password)) score++;
            else feedback.push('包含大写字母');

            if (/\d/.test(password)) score++;
            else feedback.push('包含数字');

            if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) score++;
            else feedback.push('包含特殊字符');

            let strength = '';
            let className = '';
            if (score < 3) {
                strength = '弱';
                className = 'strength-weak';
            } else if (score < 4) {
                strength = '中等';
                className = 'strength-medium';
            } else {
                strength = '强';
                className = 'strength-strong';
            }

            strengthDiv.innerHTML = `<span class="${className}">密码强度：${strength}</span>`;
            if (feedback.length > 0) {
                strengthDiv.innerHTML += `<br><small>建议：${feedback.join('、')}</small>`;
            }
        }

        // 实时验证
        passwordInput.addEventListener('input', function() {
            checkPasswordStrength(this.value);
            validatePassword();
        });

        confirmPasswordInput.addEventListener('input', validateConfirmPassword);
        usernameInput.addEventListener('input', validateUsername);
        emailInput.addEventListener('input', validateEmail);
        phoneInput.addEventListener('input', validatePhone);

        // 验证函数
        function validateUsername() {
            const username = usernameInput.value.trim();
            const errorDiv = document.getElementById('usernameError');
            
            if (!username) {
                usernameInput.classList.remove('is-valid');
                usernameInput.classList.add('is-invalid');
                errorDiv.textContent = '用户名不能为空';
                return false;
            }
            
            if (username.length < 3 || username.length > 20) {
                usernameInput.classList.remove('is-valid');
                usernameInput.classList.add('is-invalid');
                errorDiv.textContent = '用户名长度必须在3-20个字符之间';
                return false;
            }
            
            if (!/^[a-zA-Z0-9_]+$/.test(username)) {
                usernameInput.classList.remove('is-valid');
                usernameInput.classList.add('is-invalid');
                errorDiv.textContent = '用户名只能包含字母、数字和下划线';
                return false;
            }
            
            usernameInput.classList.remove('is-invalid');
            usernameInput.classList.add('is-valid');
            errorDiv.textContent = '';
            return true;
        }

        function validatePassword() {
            const password = passwordInput.value;
            const errorDiv = document.getElementById('passwordError');
            
            if (!password) {
                passwordInput.classList.remove('is-valid');
                passwordInput.classList.add('is-invalid');
                errorDiv.textContent = '密码不能为空';
                return false;
            }
            
            if (password.length < 6 || password.length > 20) {
                passwordInput.classList.remove('is-valid');
                passwordInput.classList.add('is-invalid');
                errorDiv.textContent = '密码长度必须在6-20个字符之间';
                return false;
            }
            
            if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/.test(password)) {
                passwordInput.classList.remove('is-valid');
                passwordInput.classList.add('is-invalid');
                errorDiv.textContent = '密码必须包含至少一个小写字母、一个大写字母和一个数字';
                return false;
            }
            
            passwordInput.classList.remove('is-invalid');
            passwordInput.classList.add('is-valid');
            errorDiv.textContent = '';
            return true;
        }

        function validateConfirmPassword() {
            const password = passwordInput.value;
            const confirmPassword = confirmPasswordInput.value;
            const errorDiv = document.getElementById('confirmPasswordError');
            
            if (!confirmPassword) {
                confirmPasswordInput.classList.remove('is-valid');
                confirmPasswordInput.classList.add('is-invalid');
                errorDiv.textContent = '请确认密码';
                return false;
            }
            
            if (password !== confirmPassword) {
                confirmPasswordInput.classList.remove('is-valid');
                confirmPasswordInput.classList.add('is-invalid');
                errorDiv.textContent = '两次输入的密码不一致';
                return false;
            }
            
            confirmPasswordInput.classList.remove('is-invalid');
            confirmPasswordInput.classList.add('is-valid');
            errorDiv.textContent = '';
            return true;
        }

        function validateEmail() {
            const email = emailInput.value.trim();
            const errorDiv = document.getElementById('emailError');
            
            if (!email) {
                emailInput.classList.remove('is-valid');
                emailInput.classList.add('is-invalid');
                errorDiv.textContent = '邮箱不能为空';
                return false;
            }
            
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                emailInput.classList.remove('is-valid');
                emailInput.classList.add('is-invalid');
                errorDiv.textContent = '邮箱格式不正确';
                return false;
            }
            
            emailInput.classList.remove('is-invalid');
            emailInput.classList.add('is-valid');
            errorDiv.textContent = '';
            return true;
        }

        function validatePhone() {
            const phone = phoneInput.value.trim();
            const errorDiv = document.getElementById('phoneError');
            
            if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
                phoneInput.classList.remove('is-valid');
                phoneInput.classList.add('is-invalid');
                errorDiv.textContent = '手机号格式不正确';
                return false;
            }
            
            phoneInput.classList.remove('is-invalid');
            if (phone) phoneInput.classList.add('is-valid');
            errorDiv.textContent = '';
            return true;
        }

        function validateForm() {
            const isValid = validateUsername() && 
                           validatePassword() && 
                           validateConfirmPassword() && 
                           validateEmail() && 
                           validatePhone() &&
                           roleSelect.value;
            
            if (!roleSelect.value) {
                roleSelect.classList.add('is-invalid');
            } else {
                roleSelect.classList.remove('is-invalid');
            }
            
            return isValid;
        }

        // 显示错误信息
        function showError(message) {
            errorMessage.textContent = message;
            errorAlert.style.display = 'block';
            successAlert.style.display = 'none';
            setTimeout(() => {
                errorAlert.style.display = 'none';
            }, 5000);
        }

        // 显示成功信息
        function showSuccess(message) {
            successMessage.textContent = message;
            successAlert.style.display = 'block';
            errorAlert.style.display = 'none';
        }

        // 显示加载状态
        function showLoading() {
            registerBtn.disabled = true;
            loadingSpinner.style.display = 'inline-block';
            registerText.textContent = '注册中...';
        }

        // 隐藏加载状态
        function hideLoading() {
            registerBtn.disabled = false;
            loadingSpinner.style.display = 'none';
            registerText.textContent = '注册账号';
        }

        // 注册请求
        async function register(formData) {
            try {
                const response = await fetch(`${API_BASE_URL}/auth/register`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(formData)
                });

                const data = await response.json();

                if (data.success) {
                    showSuccess('注册成功！请使用新账号登录');
                    setTimeout(() => {
                        window.location.href = 'login.html';
                    }, 2000);
                } else {
                    showError(data.message || '注册失败');
                }
            } catch (error) {
                console.error('注册错误:', error);
                showError('网络错误，请检查连接');
            }
        }

        // 表单提交
        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            if (!validateForm()) {
                showError('请检查表单输入');
                return;
            }

            const formData = {
                username: usernameInput.value.trim(),
                password: passwordInput.value,
                confirmPassword: confirmPasswordInput.value,
                fullName: fullNameInput.value.trim(),
                email: emailInput.value.trim(),
                phone: phoneInput.value.trim() || null,
                role: roleSelect.value,
                department: document.getElementById('department').value.trim() || null,
                position: document.getElementById('position').value.trim() || null,
                employeeId: document.getElementById('employeeId').value.trim() || null
            };

            showLoading();
            await register(formData);
            hideLoading();
        });

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 检查是否已经登录
            const token = localStorage.getItem('token');
            if (token) {
                // 如果已登录，跳转到对应仪表板
                const user = JSON.parse(localStorage.getItem('user') || '{}');
                if (user.role) {
                    switch(user.role) {
                        case 'ADMIN':
                            window.location.href = 'admin-dashboard.html';
                            break;
                        case 'AGENT':
                            window.location.href = 'agent-dashboard.html';
                            break;
                        case 'CUSTOMER':
                            window.location.href = 'customer-dashboard.html';
                            break;
                    }
                }
            }
        });
    </script>
</body>
</html>
